from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from datetime import datetime, timedelta
import json


@login_required
def dashboard(request):
    """仪表板页面"""
    # 提供图表所需的默认数据
    context = {
        'file_type_labels': json.dumps(['Excel', 'CSV', 'TXT', '其他']),
        'file_type_data': json.dumps([0, 0, 0, 0]),
        'trend_labels': json.dumps([]),
        'completed_tasks': json.dumps([]),
        'failed_tasks': json.dumps([])
    }
    return render(request, 'dashboard/dashboard.html', context)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def dashboard_stats(request):
    """获取仪表板统计数据"""
    try:
        from apps.core.models import ProcessingTask, UploadedFile
        
        # 获取任务统计
        total_tasks = ProcessingTask.objects.count()
        pending_tasks = ProcessingTask.objects.filter(status='pending').count()
        running_tasks = ProcessingTask.objects.filter(status='running').count()
        completed_tasks = ProcessingTask.objects.filter(status='completed').count()
        failed_tasks = ProcessingTask.objects.filter(status='failed').count()
        
        # 获取文件统计
        total_files = UploadedFile.objects.count()
        
        # 获取最近7天的任务趋势
        end_date = datetime.now().date()
        start_date = end_date - timedelta(days=6)
        
        task_trend = []
        for i in range(7):
            date = start_date + timedelta(days=i)
            count = ProcessingTask.objects.filter(
                created_at__date=date
            ).count()
            task_trend.append({
                'date': date.isoformat(),
                'count': count
            })
        
        # 获取系统统计
        try:
            import psutil
            cpu_percent = psutil.cpu_percent(interval=1)
            memory = psutil.virtual_memory()
            disk = psutil.disk_usage('/')
            
            system_stats = {
                'cpu': {'percent': cpu_percent},
                'memory': {
                    'percent': memory.percent,
                    'used': memory.used // (1024 * 1024),
                    'total': memory.total // (1024 * 1024)
                },
                'disk': {
                    'percent': (disk.used / disk.total) * 100,
                    'used': disk.used // (1024 * 1024 * 1024),
                    'total': disk.total // (1024 * 1024 * 1024)
                }
            }
        except:
            system_stats = {
                'cpu': {'percent': 0},
                'memory': {'percent': 0, 'used': 0, 'total': 0},
                'disk': {'percent': 0, 'used': 0, 'total': 0}
            }
        
        data = {
            'tasks': {
                'total': total_tasks,
                'pending': pending_tasks,
                'running': running_tasks,
                'completed': completed_tasks,
                'failed': failed_tasks,
                'trend': task_trend
            },
            'files': {
                'total': total_files
            },
            'system': system_stats
        }
        
        return Response(data, status=status.HTTP_200_OK)
        
    except Exception as e:
        return Response({
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
